package com.toilet.easyvideo.security;

import cn.hutool.json.JSONUtil;
import com.toilet.easyvideo.constant.HttpStatus;
import com.toilet.easyvideo.constant.StringConstant;
import com.toilet.easyvideo.handler.ResponseResult;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import java.io.IOException;

public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        if (authException instanceof LockedException) {
            returnResponse(response, "账户被锁定，请联系管理员!");
        } else if (authException instanceof CredentialsExpiredException) {
            returnResponse(response, "账户被锁定，用户名或者密码输入错误!");
        } else if (authException instanceof InsufficientAuthenticationException) {
            returnResponse(response, "权限不足请登录!");
        } else if (authException instanceof AccountExpiredException) {
            returnResponse(response, "账户过期，请联系管理员!");
        } else if (authException instanceof DisabledException) {
            returnResponse(response, "账户被禁用，请联系管理员!");
        } else if (authException instanceof BadCredentialsException) {
            returnResponse(response, "用户名或者密码输入错误!");
        } else if (authException instanceof AuthenticationServiceException) {
            returnResponse(response, "认证失败，请重试!");
        }
    }

    private void returnResponse(HttpServletResponse response, String errorMsg) throws IOException {
        response.setCharacterEncoding(StringConstant.UTF8);
        ResponseResult result = new ResponseResult(HttpStatus.FORBIDDEN, errorMsg);
        response.getWriter().write(JSONUtil.toJsonStr(result));
    }
}
